<template>
  <div class="page-mobile_poster">
    <div class="poster">
      <img
        id="poster"
        ref="posterImg"
        alt
        style="width: 750px;height: 1200px;"
      />
    </div>
    <div class="poster_url" id="poster_box" style="display:none;">
      <img id="poster_url" src="" alt style="width: 300px;height: 480px;" />
    </div>
    <div id="qrcode" style="display:none"></div>
    <canvas id="myCanvas"></canvas>
    <div class="tips">长按<span>保存</span>上方海报</div>
  </div>
</template>

<script>
import { getDistributionInfo, getQrcode } from "~/api/distribution";
import { mapState, mapActions, mapMutations } from "vuex";
import { downloadFile } from "~/api/common";
import { fileToBase64 } from "~/utils/file";
export default {
  components: {},
  scrollToTop: true,
  data() {
    return {
      distribution_info: {}
    };
  },

  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      }
    })
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        var year = _date.getFullYear();
        var month = _date.getMonth() + 1;
        var date = _date.getDate();
        var hours = _date.getHours();
        var minutes = _date.getMinutes();
        if (month < 10) {
          month = "0" + month;
        }
        if (date < 10) {
          date = "0" + date;
        }
        if (hours < 10) {
          hours = "0" + hours;
        }
        if (minutes < 10) {
          minutes = "0" + minutes;
        }
        return year + "." + month + "." + date + " " + hours + ":" + minutes;
        // return `${_date.getFullYear()}.${_date.getMonth() +
        //   1}.${_date.getDate()} ${_date.getHours()}:${'0'+_date.getMinutes()}`;
      } else {
        return "未知";
      }
    },
    toPath(path) {
      this.$router.push(path);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log("上拉加载");
        if (this.total <= this.withdrawal_log_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    async getDistributionInfo() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id
      };
      let result = await getDistributionInfo(params);
      // console.log("执行");
      if (result && result.data && result.data.code == 200) {
        this.distribution_info = result.data.data;
        this.setImg(() => {
          let url =
            window.location.origin + "/regist?fatherId=" + this.user_info.id;
          let qrcode = new QRCode(document.getElementById("qrcode"), {
            text: url,
            correctLevel: QRCode.CorrectLevel.L,
            width: 150,
            height: 150
          });
          // qrcode.makeCode(url);
          // let qrcodeImg = document.getElementById("qrcode").lastChild;
          let qrcodeUrl = qrcode._oDrawing._elCanvas.toDataURL();
          let qrcodeImg = new Image();
          qrcodeImg.src = qrcodeUrl;

          qrcodeImg.onload = () => {
            let bgImg = document.getElementById("poster");
            console.log("bgImg:", bgImg);
            let canvas = document.getElementById("myCanvas");
            canvas.width = parseInt(bgImg.style.width);
            canvas.height = parseInt(bgImg.style.height);
            let ctx = canvas.getContext("2d");
            ctx.drawImage(
              bgImg,
              0,
              0,
              parseInt(bgImg.style.width),
              parseInt(bgImg.style.height)
            );
            ctx.rect(295, 945, 160, 160);
            ctx.fillStyle = "#ffffff";
            ctx.fill();

            console.log("qrcodeImg:", qrcodeImg);
            ctx.drawImage(
              qrcodeImg,
              300, 
              950,
              parseInt(qrcodeImg.width),
              parseInt(qrcodeImg.height)
            );
            let image = document.getElementById("poster_url");
            let posterBox = document.getElementById("poster_box");
            image.src = canvas.toDataURL("image/png");
            canvas.style.display = "none";
            posterBox.style.display = "block";
            this.SET_IS_LOADING(false);
          };
        });
      } else {
        // this.$Message.error("获取失败！");
        this.$toast("获取失败！");
        this.SET_IS_LOADING(false);
      }
    },
    async getData(fetch_type) {
      this.SET_IS_LOADING(true);
      let result = await getWithdrawalLog({
        sort: "id desc",
        offset: this.pageSize * (this.page - 1),
        limit: this.pageSize,
        userId: this.user_info.id
      });
      if (result && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.withdrawal_log_list = [
            ...this.withdrawal_log_list,
            ...result.data.data.rows
          ];
        } else {
          this.withdrawal_log_list = result.data.data.rows;
        }
        // this.withdrawal_log_list.sort(function (a, b) {
        //   return b.createTime - a.createTime;
        // });
        this.total = result.data.data.total;
        this.records = result.data.data.records;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("获取失败！");
      }
    },
    async setImg(callback) {
      const { posterUrl } = this.distribution_info;
      let result = await downloadFile(posterUrl);
      fileToBase64(result.data, res => {
        console.log("posterImgFile:", res);
        this.$refs.posterImg.src = res;
        this.$refs.posterImg.onload = () => {
          callback();
        };
      });
    }
  },
  activated() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  created() {
    // this.getData();
    this.getDistributionInfo();
    
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile_poster {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background-color: var(--theme-color);
  #myCanvas {
    margin: 70px auto 0;
  }
  .poster,
  .poster_url {
    width: 100%;
    text-align: center;
    > img {
      margin-top: 70px;
      width: 300px;
      height: 480px;
    }
  }
  .poster {
    visibility: hidden;
    z-index: 0;
    position: absolute;
    z-index: -1;
  }
  .tips {
    // position: fixed;
    // bottom: 0;
    // left: 0;
    color: #ffffff;
    font-size: 20px;
    text-align: center;
    line-height: 2;
    > span {
      padding: 0 5px;
      font-weight: 700;
    }
  }
}
</style>
<style lang="scss">
.page-mobile_poster {
  .van-tabs__wrap {
    // position: relative;
    height: 0.8rem;
    // z-index: 999;
    &::after {
      position: relative;
      z-index: 998;
      height: 0.8rem;
    }
  }
  .van-tabs__nav--line {
    position: fixed;
    z-index: 999;
    top: 0.8rem;
    width: 100%;
    height: 0.8rem;
    &::after {
      content: "";
      position: absolute;
      //   bottom: 15px;
      bottom: 0;
      left: 0;
      width: 100%;
      display: block;
      background-color: transparent;
      border-bottom: 0.02rem solid #ebedf0;
    }
  }
  .van-tabs__nav--line {
    padding-bottom: 0px;
  }
  .van-tabs__line {
    bottom: 0px;
  }
  .team-item {
    // margin-top: 15px;
    // z-index: 1000;
    padding: 0.2rem 0.2rem;
    // line-height: 1;

    img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: var(--theme-color);
      vertical-align: middle;
    }
    .van-cell__value {
      display: none;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .cell-dot {
      &::before {
        visibility: hidden;
      }
      .van-info {
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
}
</style>
